import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import axios from '../utils/axios';  // 使用配置好的 axios 实例
import { useAuth } from './AuthContext';

const ActivityContext = createContext();

export function ActivityProvider({ children }) {
  const [activities, setActivities] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const { user } = useAuth();

  // 获取用户活动列表
  const fetchActivities = useCallback(async () => {
    if (!user) return;
    
    try {
      setLoading(true);
      const response = await axios.get('/api/resources/user/activities');
      setActivities(response.data);
    } catch (error) {
      console.error('获取活动失败:', error);
      setError(error.response?.data?.message || '获取活动失败');
    } finally {
      setLoading(false);
    }
  }, [user]);

  // 参与活动
  const joinActivity = async (activityId) => {
    try {
      await axios.post(`/resources/${activityId}/join`);
      await fetchActivities(); // 重新获取活动列表
      return true;
    } catch (error) {
      setError(error.response?.data?.message || '参与活动失败');
      return false;
    }
  };

  // 活动打卡
  const checkInActivity = async (activityId, data) => {
    try {
      const response = await axios.post(`/resources/${activityId}/checkin`, data);
      await fetchActivities(); // 重新获取活动列表
      return response.data;
    } catch (error) {
      setError(error.response?.data?.message || '打卡失败');
      throw error;
    }
  };

  // 当用户登录状态改变时获取活动
  useEffect(() => {
    if (user) {
      fetchActivities();
    } else {
      setActivities([]);
    }
  }, [user, fetchActivities]);

  return (
    <ActivityContext.Provider value={{
      activities,
      loading,
      error,
      fetchActivities,
      joinActivity,
      checkInActivity
    }}>
      {children}
    </ActivityContext.Provider>
  );
}

export function useActivities() {
  return useContext(ActivityContext);
} 